/*
 * Copyright (C) 2019 @MTI Ltd.
 *
 */
package com.mti.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.FutureTask;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSON;
import com.mti.kafka.Producer;
import com.mti.kafka.entity.ZdryEntity;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DefaultDataBuffer;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.component.snowflake.KeyWorker;
import com.mti.configuration.SystemConfig;
import com.mti.dao.dto.ZdryDto;
import com.mti.dao.model.ContactCardPoliceForceEntity;
import com.mti.dao.model.ContactPoliceRoomEntity;
import com.mti.dao.model.KmZdryAssistEntity;
import com.mti.dao.model.KmZdryCustomEntity;
import com.mti.dao.model.KmZdryHomeEntity;
import com.mti.dao.model.KmZdryTypeEntity;
import com.mti.dao.model.KmZdryZrbmEntity;
import com.mti.dao.model.LfRyyjsjEntity;
import com.mti.dao.model.LfZdryApproveLogEntity;
import com.mti.dao.model.LfZdryControlPcEntity;
import com.mti.dao.model.LfZdryControlPcReceiveEntity;
import com.mti.dao.model.LfZdryEntity;
import com.mti.dao.model.LfZdryHistoryLogEntity;
import com.mti.dao.model.LfZdryTempEntity;
import com.mti.dao.model.LfZdryZrbmEntity;
import com.mti.dao.model.SysDictEntity;
import com.mti.dao.model.TTaskFileEntity;
import com.mti.dao.qo.AddressQO;
import com.mti.dao.qo.LfZdryQO;
import com.mti.enums.ApproveStatus;
import com.mti.enums.RoleType;
import com.mti.enums.UpdateType;
import com.mti.exception.BusinessException;
import com.mti.jwt.AccountBo;
import com.mti.jwt.RequestUtils;
import com.mti.mapper.LfZdryMapper;
import com.mti.mapper.LfZdryTempMapper;
import com.mti.service.CacheableService;
import com.mti.service.IContactCardPoliceForceService;
import com.mti.service.IContactPoliceRoomService;
import com.mti.service.ILfGkjlService;
import com.mti.service.ILfZdryControlPcReceiveService;
import com.mti.service.ILfZdryControlPcService;
import com.mti.service.ILfZdryService;
import com.mti.service.ILfZdryZrbmService;
import com.mti.service.ISysDictService;
import com.mti.service.KmZdryAssistService;
import com.mti.service.KmZdryCustomService;
import com.mti.service.KmZdryHomeService;
import com.mti.service.KmZdryTypeService;
import com.mti.service.KmZdryZrbmService;
import com.mti.service.LfZdryHistoryLogService;
import com.mti.service.TTaskFileService;
import com.mti.utils.AddressResolutionUtil;
import com.mti.utils.DateUtils;
import com.mti.utils.GetImage;
import com.mti.utils.ListUtils;
import com.mti.utils.StrUtils;
import com.mti.vo.PredictStatisticsDataItem;
import com.mti.vo.ZdryVo;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 
 * @author chenf
 * @since 2019-04-29
 */
@Slf4j
@Service
public class LfZdryServiceImpl extends ServiceImpl<LfZdryMapper, LfZdryEntity> implements ILfZdryService {



	@Value("${zdry.txUrl}")
	private String zdryTxUrl; // 注入配置属性

	@Value("${zdry.txFileAddr}")
	private String zdryTxFileAddr; // 注入配置属性

	@Autowired
	private ISysDictService service;

	@Resource
	private LfZdryMapper mapper;

	@Resource
	private LfZdryTempMapper tempZdryMapper;

	@Autowired
	private ILfZdryZrbmService zdryZrbmService;

	@Autowired
	IContactCardPoliceForceService contactCardPoliceForceService;

	@Autowired
	IContactPoliceRoomService contactPoliceRoomService;

	@Autowired
	ILfZdryControlPcService lfZdryControlPcService;

	@Autowired
	ILfZdryControlPcReceiveService lfZdryControlPcReceiveService;

	@Autowired
	private ILfGkjlService gkjlService;

	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	private SystemConfig systemConfig;

	@Autowired
	private RequestUtils requestUtils;

	/*@Autowired
	private ISpecialPersonService specialPersonService;*/
	
	@Autowired
    private SpecialPersonComponent specialPersonComponent;
	
	@Autowired
    private ISysDictService iSysDictService;
	
	@Autowired
	private CacheableService cacheableService;
	@Autowired
	private ExecutorService executorService;

	/*@Autowired
	private LfZdryBaseService lfZdryBaseService;*/
	
	@Autowired
	private KmZdryTypeService kmZdryTypeService;
	
	@Autowired
	private KmZdryHomeService kmZdryHomeService;
	
	@Autowired
	private KmZdryCustomService kmZdryCustomService;
	
	@Autowired
	private KmZdryAssistService kmZdryAssistService;
	
	@Autowired
	private LfZdryHistoryLogService lfZdryHistoryLogService;

	@Autowired
	private KmZdryZrbmService kmZdryZrbmService;
 
	@Autowired
	private TTaskFileService taskFileService; 	
	@Override
	public LfZdryEntity getByXh(String id) {
		return this.getOne(new QueryWrapper<LfZdryEntity>().eq("xh", id).lambda());
	}

	@Override
	public ZdryDto getBySfzh(String sfzh) {
		/*LfZdryBaseEntity baseEntity =  lfZdryBaseService.getOne(new QueryWrapper<LfZdryBaseEntity>().eq("sfzh", sfzh).lambda().last("LIMIT 1"));
		ZdryDto dto =  (ZdryDto)baseEntity;
		List<KmZdryCustomEntity> customList =kmZdryCustomService.list(new QueryWrapper<KmZdryCustomEntity>().eq("zdry_id", dto.getId()));
		dto.setCustomList(customList)	;
		List<KmZdryTypeEntity> typeList =kmZdryTypeService.list(new QueryWrapper<KmZdryTypeEntity>().eq("zdry_id", dto.getId()));
		dto.setTypeList(typeList);
		List<KmZdryAssistEntity> AssistList =kmZdryAssistService.list(new QueryWrapper<KmZdryAssistEntity>().eq("zdry_id", dto.getId()));
		dto.setAssistList(AssistList)	;
		List<KmZdryHomeEntity> HomeList =kmZdryHomeService.list(new QueryWrapper<KmZdryHomeEntity>().eq("zdry_id", dto.getId()));
		dto.setJzdList(HomeList)	;
		return  dto;*/
		return null;
				 
	}

	@Override
	public LfZdryEntity getBySfzhV2(String sfzh) {
		return this.getOne(new QueryWrapper<LfZdryEntity>().eq("sfzh", sfzh).lambda().last("LIMIT 1"));
	}

	public LfZdryZrbmEntity getByZrbm(String rylbx) {
		return mapper.getByZrbm(rylbx);
	}

	@Override
	public List<LfZdryZrbmEntity> getAllRylxWithZrbm() {
		return zdryZrbmService.list();
	}

	public LfRyyjsjEntity getByBjxx(String sfzh, String datetime, String eventType) {
		LfRyyjsjEntity entity = new LfRyyjsjEntity();
		if (eventType.equals("1")) {
			if (StringUtils.isNotBlank(sfzh) && StringUtils.isNotBlank(datetime)) {
				String datetimeStr = datetime.replace("-", "").replace(" ", "").replace(":", "");
				entity = mapper.getByZdryBjxx(sfzh, datetimeStr);
			}
		} else if (eventType.equals("2")) {
			if (StringUtils.isNotBlank(sfzh) && StringUtils.isNotBlank(datetime)) {
				String datetimeStr = datetime.replace("-", "").replace(" ", "").replace(":", "");
				entity = mapper.getByZtryBjxx(sfzh, datetimeStr);
			}
		}
		return entity;
	}

	@Override
	public List<Map<String, String>> getCount(String cid, String zrbm, String rangeType, String rangeVal) {
		// 1：重点人员类型分析 2：是否在控 3：区域占比 4：等级分析
		List<Map<String, String>> returnList = new ArrayList<Map<String, String>>();
		List<String> rangeIds = null;
		if (!StringUtils.isEmpty(rangeType) && !StringUtils.isEmpty(rangeVal)) {
			rangeIds = Arrays.asList(rangeVal.split(","));
		}
		List<String> zrbms = null;
		if (!StringUtils.isEmpty(zrbm))
			zrbms = Arrays.asList(zrbm.split(","));
		if (cid.equals("1")) {

			return mapper.getCountByRylbx(zrbms, rangeType, rangeIds);
		} else if (cid.equals("2")) {

			return mapper.getCountBySfzk(zrbms, rangeType, rangeIds);
		} else if (cid.equals("3")) {

			return mapper.getCountBySsxq(zrbms, rangeType, rangeIds);
		} else if (cid.equals("4")) {

			return mapper.getCountByGkjbx(zrbms, rangeType, rangeIds);
		} else if (cid.equals("5")) {

			return mapper.getCountByYjlx(zrbms, rangeType, rangeIds);
		} else if (cid.equals("6")) {

			return mapper.getCountBySsxqGkjbx(zrbms, rangeType, rangeIds);
		}
		return returnList;
	}

	@Override
	public IPage<LfZdryEntity> queryPage(LfZdryQO qo) {
		Page<LfZdryEntity> page = new Page<>(qo.getStart(), qo.getSize());

		if (qo == null || (qo.getRylbxList() != null && qo.getRylbxList().size() == 0)
				|| (qo.getSfzkList() != null && qo.getSfzkList().size() == 0)
				|| (qo.getZrbmList() != null && qo.getZrbmList().size() == 0)
				|| (qo.getSsxqList() != null && qo.getSsxqList().size() == 0)
				|| (qo.getGkjbxList() != null && qo.getGkjbxList().size() == 0)
				|| (qo.getMjidList() != null && qo.getMjidList().size() == 0)
				|| (qo.getSspcsList() != null && qo.getSspcsList().size() == 0)
				|| (qo.getRylyList() != null && qo.getRylyList().size() == 0)) {
			QueryWrapper<LfZdryEntity> queryWrapper = new QueryWrapper<LfZdryEntity>();
			// queryWrapper.eq("xm","-##-");
			// queryWrapper.eq("approve_status","4");
			queryWrapper.lambda().orderByDesc(LfZdryEntity::getUpdate_timex);
			return this.page(page, queryWrapper);
		} else {
			qo.setRylbxList(ListUtils.removeNullElement(qo.getRylbxList()));
			qo.setSfzkList(ListUtils.removeNullElement(qo.getSfzkList()));
			qo.setZrbmList(ListUtils.removeNullElement(qo.getZrbmList()));
			qo.setSsxqList(ListUtils.removeNullElement(qo.getSsxqList()));
			qo.setSsxqIdList(ListUtils.removeNullElement(qo.getSsxqIdList()));
			qo.setGkjbxList(ListUtils.removeNullElement(qo.getGkjbxList()));
			qo.setMjidList(ListUtils.removeNullElement(qo.getMjidList()));
			qo.setSspcsList(ListUtils.removeNullElement(qo.getSspcsList()));
			qo.setRylyList(ListUtils.removeNullElement(qo.getRylyList()));
			// qo.setApproveStatus(ApproveStatus.COMPLETED.getStatus().toString());
			return mapper.queryPage(page, qo);
		}
	}

	@Override
	public IPage<LfZdryEntity> queryPageList(LfZdryQO qo, ServerWebExchange exchange) {
		System.out.println("================================:" + qo);
		Page<LfZdryEntity> page = new Page<>(qo.getStart(), qo.getSize());
		qo.setRylbxList(ListUtils.removeNullElement(qo.getRylbxList()));
		qo.setSfzkList(ListUtils.removeNullElement(qo.getSfzkList()));
		qo.setZrbmList(ListUtils.removeNullElement(qo.getZrbmList()));
		qo.setSsxqList(ListUtils.removeNullElement(qo.getSsxqList()));
		qo.setSsxqIdList(ListUtils.removeNullElement(qo.getSsxqIdList()));
		qo.setGkjbxList(ListUtils.removeNullElement(qo.getGkjbxList()));
		qo.setMjidList(ListUtils.removeNullElement(qo.getMjidList()));
		qo.setSspcsList(ListUtils.removeNullElement(qo.getSspcsList()));
		qo.setRylyList(ListUtils.removeNullElement(qo.getRylyList()));
		// qo.setApproveStatus(ApproveStatus.COMPLETED.getStatus().toString());
		//新增户籍省市县查询
		Map<String,String> regiones = this.getAllRegionInfo();
		log.error("==========================regiones==========================:"+regiones); 
		List<String[]> hjssxList = new ArrayList<String[]>();
		if(qo.getHjssxList()!=null) {
			for (String[] ssxs : qo.getHjssxList()) {
				String [] ssxChar = new String[3];
				for (int i = 0; i < ssxs.length; i++) {
					ssxChar[i]=regiones.get(ssxs[i]);
				}
				hjssxList.add(ssxChar);
			}
			qo.setHjssxList(hjssxList);
		}
		// 权限相关代码
		AccountBo bo = requestUtils.getCurrentUser(exchange);
		if (bo == null) {
			throw new BusinessException(10019,"此账号已在别处登录，请查证");
		}
		String roleType = bo.getRoleList().get(0).getRoleType();
		String orgName = bo.getOrganizationBo().getShortName();
		// getOrgName(bo.getOrgId());
		// 1、管理员、市局情报中心,不加判断条件
		// 2、市局各警种
		// 角色类型："管理员", "0")"市局情报中心", "1"), "市局警种", "2"),"分局", "3"),"派出所", "4")
		// 审批状态：0：待分局审批,1：待警种审核,2：已驳回,3：已完成, 4：上报
		if (roleType.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 1:市局情报中心
			qo.setSsxqList(qo.getQueryList());
		} else if (roleType.equals(RoleType.OWNER_REVIEW_DATA.getType())
				|| roleType.equals(RoleType.OWNER_ORG_DATA.getType())) { // 5:市局警种和2:市局警种审核
			qo.setZrbm(orgName);
			qo.setSsxqList(qo.getQueryList());
		} else if (roleType.equals(RoleType.BREACH_REVIEW_DATA.getType())
				|| roleType.equals(RoleType.BREACH_DATA.getType())) { // 6:分局 和 3:分局审核
			qo.setSsxq(orgName);
			log.info("============qo=========:" + qo);
			/*
			 * if(qo.getQueryList()!=null&&!qo.getQueryList().contains("其他")) { }
			 */
			if(null!=qo.getQueryList()) {
				List<String> list = new ArrayList<String>();
				for (String pcs : qo.getQueryList()) {
					list.add(qo.getSsxq() + pcs);
				}
				qo.setSspcsList(list);
			}
		} else if (roleType.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所4
			qo.setSspcs(orgName);
			qo.setMjList(qo.getQueryList());
			/*if (qo.getQueryList() != null && !qo.getQueryList().contains("其他")) {
			} else if (qo.getQueryList() != null && qo.getQueryList().contains("其他")) {
				// 未指定民警的 查询条件
				qo.getQueryList().remove("其他");
				qo.setMjList(qo.getQueryList());
				return mapper.otherQueryPage(page, qo);
			}*/
		}
		return mapper.queryPage(page, qo);
	}

	@Override
	public IPage<LfZdryTempEntity> queryPageStatyReviewedList(LfZdryQO qo, ServerWebExchange exchange) {
		Page<LfZdryEntity> page = new Page<>(qo.getStart(), qo.getSize());
		qo.setRylbxList(ListUtils.removeNullElement(qo.getRylbxList()));
		qo.setSfzkList(ListUtils.removeNullElement(qo.getSfzkList()));
		qo.setZrbmList(ListUtils.removeNullElement(qo.getZrbmList()));
		qo.setSsxqList(ListUtils.removeNullElement(qo.getSsxqList()));
		qo.setSsxqIdList(ListUtils.removeNullElement(qo.getSsxqIdList()));
		qo.setGkjbxList(ListUtils.removeNullElement(qo.getGkjbxList()));
		qo.setMjidList(ListUtils.removeNullElement(qo.getMjidList()));
		qo.setSspcsList(ListUtils.removeNullElement(qo.getSspcsList()));
		qo.setRylyList(ListUtils.removeNullElement(qo.getRylyList()));
		// qo.setApproveStatus(ApproveStatus.COMPLETED.getStatus().toString());
		//新增户籍省市县查询
		Map<String,String> regiones = this.getAllRegionInfo();
		log.error("==========================regiones==========================:"+regiones); 
		List<String[]> hjssxList = new ArrayList<String[]>();
		for (String[] ssxs : qo.getHjssxList()) {
			String [] ssxChar = new String[ssxs.length];
			for (int i = 0; i < ssxs.length; i++) {
				ssxChar[i]=regiones.get(ssxs[i]);
			}
			hjssxList.add(ssxChar);
		}
		qo.setHjssxList(hjssxList);
		// 权限相关代码
		AccountBo bo = requestUtils.getCurrentUser(exchange);
		if (bo == null) {
			throw new BusinessException(10019,"此账号已在别处登录，请查证");
		}
		String roleType = bo.getRoleList().get(0).getRoleType();
		String orgName = bo.getOrganizationBo().getShortName();
		qo.setSubmitter(bo.getId());
		// getOrgName(bo.getOrgId());
		// 1、管理员、市局情报中心,不加判断条件
		// 2、市局各警种
		// 角色类型："管理员", "0")"市局情报中心", "1"), "市局警种", "2"),"分局", "3"),"派出所", "4")
		// 审批状态：0：已驳回,1：待分局审批,2：待警种审核,3：待情报中心审核, 4：审核完毕
		if (roleType.equals(RoleType.OWNER_REVIEW_DATA.getType())
				|| roleType.equals(RoleType.OWNER_ORG_DATA.getType())) { // 5:市局警种和2:市局警种审核
			qo.setZrbm(orgName);
			qo.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
			qo.setSsxqList(qo.getQueryList());
		} else if (roleType.equals(RoleType.BREACH_REVIEW_DATA.getType())
				|| roleType.equals(RoleType.BREACH_DATA.getType())) { // 6:分局 和 3:分局审核
			qo.setSsxq(orgName);
			qo.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
			// 右下角管辖派出所 ==== 派出所不为空
			/*
			 * if(qo.getQueryList()!=null&&!qo.getQueryList().contains("其他")) { }
			 */
			List<String> list = new ArrayList<String>();
			for (String pcs : qo.getQueryList()) {
				list.add(qo.getSsxq() + pcs);
			}
			qo.setSspcsList(list);
		} else if (roleType.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所4
			qo.setSspcs(orgName);
			qo.setApproveStatus(ApproveStatus.REJECT_REVIEWED.getStatus());
			qo.setMjList(qo.getQueryList());
			 
		}

		return tempZdryMapper.queryPage(page, qo);
	}
	@Override
	@Transactional
	public boolean saveZdry(ServerWebExchange exchange, ZdryDto entity) {
		long startTime = new Date().getTime();
        //Map<String,String> regiones = service.getAllRegionInfo();
        Map<String,String> zrpcses = cacheableService.getZrpcs("3");
        entity.setSspcs(zrpcses.get(entity.getSspcs())); //设置责任派出所
        //责任管控分局
        SysDictEntity sysDictEntity =iSysDictService.getEntityByKey("kp_zrgkfj",entity.getSsxqId());
        if(null != sysDictEntity){
            entity.setSsxq(sysDictEntity.getValue());
        }
        SysDictEntity gksysDictEntity = iSysDictService.getEntityByKey("kp_gkjb",entity.getGkjb());
        if(null != gksysDictEntity){
            //entity.setGkjbx(gksysDictEntity.getValue());
        }
        
        // 获取性别
        if(StringUtils.isNotBlank(entity.getSfzh())) {
        	String id17 = entity.getSfzh().substring(16, 17);
        	if (Integer.parseInt(id17) % 2 != 0) {
        		entity.setXb("男");
        	} else {
        		entity.setXb("女");
        	}
        }
        AccountBo bo = requestUtils.getCurrentUser(exchange);
        //流程相关的逻辑
        if(bo!=null) {
        	entity.setSubmitter(bo.getId());
        	String role=  bo.getRoleList().get(0).getId();
        	entity.setSubmitterRoleId(role);
           if(role.equals(RoleType.POLICE_STATION_DATA.getType())){ //派出所用户
        	   entity.setProcessType(1);
	           entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());  
	       }else if(role.equals(RoleType.BREACH_REVIEW_DATA.getType())){ // 分局用户
	    	   entity.setProcessType(12);
	           entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());  
	       }else if(role.equals(RoleType.OWNER_REVIEW_DATA.getType()) || role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())){   //警种和情报中心用户
	    	   entity.setProcessType(0);
	           entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus()); 
	       }
	    }else {
	    	throw new BusinessException(10019,"此账号已在别处登录，请查证");
	    }  
        boolean flag = false;
        //if (entity.getId() == null || StringUtils.isEmpty(entity.getId())){
        entity.setCreateTimex(new Date());
        entity.setZrbm(entity.getTypeList().get(0).getZrbm());
        //人员类型表保存
        for (KmZdryTypeEntity kmZdryTypeEntity : entity.getTypeList()) {
        	//Integer existCount = lfZdryBaseService.count(new QueryWrapper<LfZdryBaseEntity>().eq("sfzh",entity.getSfzh()));
                    //.eq("rylb_code",kmZdryTypeEntity.getRylbCode()).eq("xl_code",kmZdryTypeEntity.getXlCode()));
            //if(existCount>0)
            	throw new BusinessException(500,"你添加的重点人员："+entity.getXm()+"在系统中已经存在！");
//                throw new BusinessException(500,"你添加的重点人员："+entity.getXm()+"选择的人员大类："
//                        +kmZdryTypeEntity.getRylbCode()+",和人员小类："+kmZdryTypeEntity.getXlCode()+" 在系统中已经存在！");
        	//kmZdryTypeEntity.setId(String.valueOf(KeyWorker.nextId()));
        	//kmZdryTypeService.save(kmZdryTypeEntity);
		}
        //
        for (KmZdryAssistEntity kmZdryAssistEntity : entity.getAssistList()) {
        	kmZdryAssistEntity.setId(String.valueOf(KeyWorker.nextId()));
        	kmZdryAssistService.save(kmZdryAssistEntity);
		}
        
        for (KmZdryHomeEntity kmZdryHomeEntity : entity.getJzdList()) {
        	kmZdryHomeEntity.setId(String.valueOf(KeyWorker.nextId()));
        	kmZdryHomeService.save(kmZdryHomeEntity);
		}
        
        for (KmZdryCustomEntity kmZdryCustomEntity : entity.getCustomList()) {
        	kmZdryCustomEntity.setId(String.valueOf(KeyWorker.nextId()));
        	kmZdryCustomService.save(kmZdryCustomEntity);
		}
        List<TTaskFileEntity> fileList = new ArrayList<TTaskFileEntity>();
    	for (TTaskFileEntity fileEntity : entity.getFileList()) {
    		TTaskFileEntity file =new TTaskFileEntity();
    		file.setId(String.valueOf(KeyWorker.nextId()));
    		file.setBussType("7");//7 重点人员新增
    		file.setBussId(entity.getId().toString());
    		file.setFileUrl(fileEntity.getFileUrl());
    		file.setFileName(fileEntity.getFileName());
    		fileList.add(file);
		}
    	taskFileService.saveBatch(fileList);
        entity.setSfzp("1");
        entity.setId(String.valueOf(KeyWorker.nextId()));
        // 审批日志表
        LfZdryEntity sourceEntity = this.getById(entity.getId());
        //String logRecord = specialPersonComponent.getModifyInfo(entity,sourceEntity);
        LfZdryApproveLogEntity logEntity = new LfZdryApproveLogEntity();
        logEntity.setCreator(bo.getPersonBo().getName());
        logEntity.setSpId(entity.getId());
        logEntity.setApproveResult(entity.getApproveStatus());
        logEntity.setOperation("提交");
        logEntity.setOperateDept(bo.getOrganizationBo().getShortName());
        logEntity.setAddition("logRecord");
//        iSpecialPersonService.approveKMSpecialPerson(logEntity);
        if(ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus()) ) {
        	//flag = lfZdryBaseService.save(entity);
        }else {
        	LfZdryTempEntity zdry = new LfZdryTempEntity();
        	BeanUtils.copyProperties(entity, zdry);
        	flag=retBool(tempZdryMapper.insert(zdry));
        }

        //历史信息表
        LfZdryHistoryLogEntity history = new LfZdryHistoryLogEntity();
        history.setCreator(bo.getPersonBo().getName());
        history.setCreateTime(new Date());
        history.setSpId(entity.getId());
        history.setApproveResult(entity.getApproveStatus());
        history.setOperation("提交");
        history.setOperateDept(bo.getOrganizationBo().getShortName());
        history.setAddition("logRecord");
        history.setType(3);
		history.setCreateTime(new Date());
        lfZdryHistoryLogService.save(history);
        long endTime = new Date().getTime();
        log.info("执行插入花费："+(endTime-startTime)/1000);
        if(!flag) {
            throw new BusinessException(10020,"添加异常");
        }
		return flag;
	}
	
	@Override
	@Transactional
	public boolean updateZdry(ServerWebExchange exchange, LfZdryEntity entity) {
		//重点信息
		String[] keyInfos={"xm","sfzh","ssxq","sspcs","hjs","hjss","hjx","hjd","rysx","gkjb","yjczlb"};
		//基本信息
		//String[] baseInfos={"sjh","wx","qq","mxcph","sjsyclhp","gkmj","mjlxdh","hjs","hjsS","hjx","hjd","bz"};
		//警种信息
		String[] policeInfos={"rylbx","xl"};
		entity.setRylbx(entity.getRydlName());
		entity.setXl(entity.getRyxlName());
		//责任管控分局
        SysDictEntity sysDictEntity =iSysDictService.getEntityByKey("kp_zrgkfj",entity.getSsxqId());
        if(null != sysDictEntity){
            entity.setSsxq(sysDictEntity.getValue());
        }
        SysDictEntity gksysDictEntity = iSysDictService.getEntityByKey("kp_gkjb",entity.getGkjb());
        if(null != gksysDictEntity){
            entity.setGkjbx(gksysDictEntity.getValue());
        }
        Map<String,String> zrpcses = cacheableService.getZrpcs("3");
        //setUpAddress(regiones,entity);
        entity.setSspcs(zrpcses.get(entity.getSspcs())); //设置责任派出所
		FutureTask<Map<String,String>> futureTask = this.getLngLat(entity);
		 try {
             Map<String,String> map = futureTask.get();
             entity.setX(map.get("xzz_x"));
             entity.setY(map.get("xzz_y"));
             entity.setHjdX(map.get("hjd_x"));
             entity.setHjdY(map.get("hjd_y"));
         } catch (Exception e) {
             log.error("获取经纬度发生异常："+e.getMessage());
         }
		AccountBo bo = requestUtils.getCurrentUser(exchange);
		//默认的修改类型为基本信息；
		int updateType = UpdateType.BASE_INFO.getCode();
		LfZdryEntity resourceEntity = this.getById(entity.getId());
        List<String> modifyList = null;//specialPersonComponent.getModifyList(entity,resourceEntity);
        
        //修改的字段是包含警种信息，包含则直接跳出
        for (String policeInfo : policeInfos) {
        	if(modifyList.contains(policeInfo)) {
        		updateType=UpdateType.CONTROL_INFO.getCode();
        		break;
        	}

        }
        if(updateType==UpdateType.BASE_INFO.getCode()) {
        	for (String keyInfo : keyInfos) {
        		if(modifyList.contains(keyInfo)) {
            		updateType=UpdateType.BASE_INFO.getCode();
            		break;
            	}
        	}
        }
        int num = 0;
		//try {
			if (bo != null) {
				entity.setModifier(bo.getPersonBo().getName());
				entity.setUpdate_timex(new Date());
				if(updateType==UpdateType.CONTROL_INFO.getCode()) {
					KmZdryZrbmEntity zrbm = Optional.ofNullable(kmZdryZrbmService.queryZrbmByDlAndXl(entity.getRylbx(),entity.getXl())).orElse(new KmZdryZrbmEntity());
					entity.setZrbm(zrbm.getZrbm());
				}
				 // 获取性别
                if(StringUtils.isNotBlank(entity.getSfzh())) {
                	String id17 = entity.getSfzh().substring(16, 17);
                	if (Integer.parseInt(id17) % 2 != 0) {
                		entity.setXb("男");
                	} else {
                		entity.setXb("女");
                	}
                }
                
				// 临时表过度
				String role=  bo.getRoleList().get(0).getId();
				entity.setSubmitter(bo.getId());
            	entity.setSubmitterRoleId(role);
            	LfZdryTempEntity tempZdry = new LfZdryTempEntity();
            	BeanUtils.copyProperties(entity, tempZdry);
				// 基本信息修改 、警种信息修改、重点信息修改、 非警种信息修改
				// 1:baseInfo/ 2:policeInfo/ 3:keyInfo/ 4:noPoliceInfo
				if (role.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所用户
					if (updateType == UpdateType.BASE_INFO.getCode()) {
						entity.setProcessType(21);
						entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
						num = mapper.updateById(entity);
					} else if (updateType == UpdateType.BASE_INFO.getCode()) {
						// tempZdry.copy();
						tempZdry.setProcessType(2);
						tempZdry.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
						num = tempZdryMapper.insert(tempZdry);
					} else if (updateType == UpdateType.CONTROL_INFO.getCode()) {
						// tempZdry.copy();
						tempZdry.setProcessType(22);
						tempZdry.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
						num = tempZdryMapper.insert(tempZdry);
					}
				} else if (role.equals(RoleType.BREACH_REVIEW_DATA.getType())) { // 分局用户
					if (updateType == UpdateType.CONTROL_INFO.getCode()) {
						// tempZdry.copy();
						tempZdry.setProcessType(25);
						tempZdry.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
						num = tempZdryMapper.insert(tempZdry);
					}else {
						entity.setProcessType(21);
						entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
						num = mapper.updateById(entity);
					}
				} else if (role.equals(RoleType.OWNER_REVIEW_DATA.getType())) { // 警种用户
					entity.setProcessType(21);
					entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
					num = mapper.updateById(entity);
				} else if (role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 情报中心
					entity.setProcessType(21);
					entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
					num = mapper.updateById(entity);
				}
			}else {
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
			
         // 记录审批日志
			 
			//String logRecord = specialPersonComponent.getModifyInfo(entity,resourceEntity);
	   		LfZdryApproveLogEntity logEntity = new LfZdryApproveLogEntity();
	   		logEntity.setCreator(bo.getPersonBo().getName());
	   		logEntity.setSpId(entity.getId());
	   		logEntity.setApproveResult(entity.getProcessType().toString());
	   		logEntity.setOperation("修改");
	   		logEntity.setOperateDept(bo.getOrganizationBo().getShortName());
	   		//logEntity.setAddition(logRecord);
//	   		iSpecialPersonService.approveKMSpecialPerson(logEntity);
	   	//历史记录
	   		LfZdryHistoryLogEntity history = new LfZdryHistoryLogEntity();
            history.setCreator(bo.getPersonBo().getName());
   	   		history.setSpId(entity.getId());
   	   		history.setApproveResult(entity.getApproveStatus());
   	   		history.setOperation("提交");
   	   		history.setOperateDept(bo.getOrganizationBo().getShortName());
   	   		//history.setAddition(logRecord);
   	   		history.setType(3);
   	   		lfZdryHistoryLogService.save(history);
		/*} catch (Exception e) {
			log.error(e.getMessage());
		}*/
 
		return retBool(num);
	}
	

	/*@Override
	public List<LfZdryEntity> queryZdryByZrpcs(String zrpcs) {
		List<LfZdryEntity> data = this
				.list(new QueryWrapper<LfZdryEntity>().lambda().like(LfZdryEntity::getSspcs, zrpcs));
		return data;
	}*/

	/*@Override
	public Mono<DataBuffer> export(String zrpcs, String exportName) {
		QueryWrapper<LfZdryEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().like(LfZdryEntity::getSspcs, zrpcs);
		List<LfZdryEntity> list = this.list(queryWrapper);

		DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
		OutputStream outputStream = dataBuffer.asOutputStream();

		SXSSFWorkbook wb = new SXSSFWorkbook(100);
		CellStyle cellStyleCenter = wb.createCellStyle();
		CellStyle cellStyleLeft = wb.createCellStyle();
		cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
		cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
		cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
		cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
		SXSSFSheet sh = wb.createSheet();
		sh.trackAllColumnsForAutoSizing();
		LocalDate localDate = LocalDate.now();

		int totalSize = 4 + list.size();
		for (int rowNum = 0; rowNum < totalSize; rowNum++) {
			Row row = sh.createRow(rowNum);

			for (int colNum = 0; colNum < 27; colNum++) {
				Cell cell1 = row.createCell(colNum);
				String title = "";
				if (rowNum == 3) {
					switch (colNum) {
					case 0: {
						title = "序号";
					}
						break;
					case 1: {
						title = "姓名";
					}
						break;
					case 2: {
						title = "身份证";
					}
						break;
					case 3: {
						title = "电话号码";
					}
						break;
					case 4: {
						title = "微信号码";
					}
						break;
					case 5: {
						title = "qq号码";
					}
						break;
					case 6: {
						title = "名下车辆号牌";
					}
						break;
					case 7: {
						title = "实际使用车辆号牌";
					}
						break;
					case 8: {
						title = "管控责任分局";
					}
						break;
					case 9: {
						title = "责任派出所";
					}
						break;
					case 10: {
						title = "责任民警";
					}
						break;
					case 11: {
						title = "责任民警电话";
					}
						break;
					case 12: {
						title = "户籍省";
					}
						break;
					case 13: {
						title = "户籍市";
					}
						break;
					case 14: {
						title = "户籍县";
					}
						break;
					case 15: {
						title = "户籍详址";
					}
						break;
					case 16: {
						title = "实际居住省";
					}
						break;
					case 17: {
						title = "实际居住市";
					}
						break;
					case 18: {
						title = "实际居住县";
					}
						break;
					case 19: {
						title = "实际居住详址";
					}
						break;
					case 20: {
						title = "人员大类";
					}
						break;
					case 21: {
						title = "人员细类";
					}
						break;
					case 22: {
						title = "人员属性";
					}
						break;
					case 23: {
						title = "风险等级";
					}
						break;
					case 24: {
						title = "预警处置类别";
					}
						break;
					case 25: {
						title = "稳控状态";
					}
						break;
					case 26: {
						title = "备注";
					}
						break;
					}
					cell1.setCellValue(title);
				} else {
					if (rowNum > 3) {

						LfZdryEntity entity = list.get(rowNum - 4);
						if (colNum == 0)
							cell1.setCellValue(rowNum - 3);
						else {
							switch (colNum) {
							case 1: {
								cell1.setCellValue(entity.getXm());
							}
								break;
							case 2: {
								cell1.setCellValue(entity.getSfzh());
							}
								break;
							case 3: {
								cell1.setCellValue(entity.getSjh());
							}
								break;
							case 4: {
								cell1.setCellValue(entity.getWx());
							}
								break;
							case 5: {
								cell1.setCellValue(entity.getQq());
							}
								break;
							case 6: {
								cell1.setCellValue(entity.getMxcph());
							}
								break;
							case 7: {
								cell1.setCellValue(entity.getSjsyclhp());
							}
								break;
							case 8: {
								cell1.setCellValue(entity.getSsxq());
							}
								break;
							case 9: {
								cell1.setCellValue(entity.getSspcs());
							}
								break;
							case 10: {
								cell1.setCellValue(entity.getGkmj());
							}
								break;
							case 11: {
								cell1.setCellValue(entity.getMjlxdh());
							}
								break;
							case 12: {
								cell1.setCellValue(entity.getHjs());
							}
								break;
							case 13: {
								cell1.setCellValue(entity.getHjsS());
							}
								break;
							case 14: {
								cell1.setCellValue(entity.getHjx());
							}
								break;
							case 15: {
								cell1.setCellValue(entity.getHjd());
							}
								break;
							case 16: {
								cell1.setCellValue(entity.getXzzs());
							}
								break;
							case 17: {
								cell1.setCellValue(entity.getXzzsS());
							}
								break;
							case 18: {
								cell1.setCellValue(entity.getXzzx());
							}
								break;
							case 19: {
								cell1.setCellValue(entity.getXzz());
							}
								break;
							case 20: {
								cell1.setCellValue(entity.getRylbx());
							}
								break;
							case 21: {
								cell1.setCellValue(entity.getXl());
							}
								break;
							case 22: {
								SysDictEntity sysDictEntity = service.getEntityByKey("zdry_ryxx",
										String.valueOf(entity.getRysx()));
								if (null != sysDictEntity) {
									cell1.setCellValue(sysDictEntity.getValue());
								} else
									cell1.setCellValue("");
							}
								break;
							case 23: {
								cell1.setCellValue(entity.getGkjbx());
							}
								break;
							case 24: {
								SysDictEntity sysDictEntity = service.getEntityByKey("zdry_yjczlb",
										String.valueOf(entity.getYjczlb()));
								if (null != sysDictEntity) {
									cell1.setCellValue(sysDictEntity.getValue());
								} else
									cell1.setCellValue("");
							}
								break;
							case 25: {
								cell1.setCellValue(entity.getWkzt());
							}
								break;
							case 26: {
								cell1.setCellValue(entity.getBz());
							}
								break;
							}
						}
					} else

						cell1.setCellValue("");
				}
				// 设置单元格样式
				cell1.setCellStyle(cellStyleLeft);
			}
			if (rowNum == 0) {
				sh.addMergedRegion(new CellRangeAddress(0, 0, 0, 9));
				sh.getRow(rowNum).getCell(0)
						.setCellValue(org.springframework.util.StringUtils.isEmpty(exportName)
								? zrpcs + "重点人员统计(" + localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + ")"
								: exportName);
				// 设置单元格样式
				sh.getRow(rowNum).getCell(0).setCellStyle(cellStyleCenter);
			}
			if (rowNum == 1) {

				sh.addMergedRegion(new CellRangeAddress(1, 2, 0, 3));
				sh.getRow(rowNum).getCell(0)
						.setCellValue("填报日期： " + localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
			}
			if (rowNum == 2) {
				// sh.addMergedRegion(new CellRangeAddress(2,3,0,3));
				// sh.getRow(rowNum).getCell(0).setCellValue("本单位涉及人员" + list.size() + "名：在控 " +
				// zkCount + " 人,失控 " + skCount + " 人,未上报 " + wsbCount + " 人");
				sh.getRow(1).getCell(4).setCellValue("单位一把手签字：");
				sh.addMergedRegion(new CellRangeAddress(1, 2, 4, 9));
			}
		}
		for (int i = 0; i < totalSize; i++) {
			sh.autoSizeColumn(i, true);
		}
		try {
			wb.write(outputStream);
		} catch (IOException e) {
			log.error("error == >{}", e.getMessage());
		} finally {
			try {
				wb.close();
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
				log.error("error == >{}", e.getMessage());
			}
		}
		return Mono.just(dataBuffer);

	}*/

	/*@Override
	public IPage<LfZdryEntity> queryZdryByZrpcsPage(String keyWords,String zrpcs, Integer offset, Integer size) {
		Page<LfZdryEntity> page = new Page<>(offset, size);
		Map<String,Object> paramMap = new HashMap<>();
		paramMap.put("keyWords",keyWords);
		paramMap.put("zrpcs",zrpcs);
		IPage<LfZdryEntity> data = this.getBaseMapper().queryZdryByZrpcsPage(page, paramMap);
		return data;
	}*/

/*	@Override
	public Object updateWkztById(String id, String wkzt) {
		LfZdryEntity zdry = new LfZdryEntity();
		zdry.setId(id);
		zdry.setWkzt(wkzt);
		return this.updateById(zdry);
	}*/

	@Override
	public List<Map<String, Integer>> getMjControlCountByPcs(String pcs, String zrbm, String rangeType,
			String rangeVal) {
		return mapper.getMjControlCountByPcs(pcs, StringUtils.isEmpty(zrbm) ? null : Arrays.asList(zrbm.split(",")),
				rangeType,
				!StringUtils.isEmpty(rangeType) && !StringUtils.isEmpty(rangeVal) ? Arrays.asList(rangeVal.split(","))
						: null);
	}

	@Override
	public List<Map<String, Integer>> getSpByHjs(String province, String zrbm, String rangeType, String rangeVal,
			String areaLevel) {
		return mapper.getSpByHjs(province, StringUtils.isEmpty(zrbm) ? null : Arrays.asList(zrbm.split(",")), rangeType,
				!StringUtils.isEmpty(rangeType) && !StringUtils.isEmpty(rangeVal) ? Arrays.asList(rangeVal.split(","))
						: null,
				StringUtils.isEmpty(areaLevel) ? "hjs"
						: "hjs".equalsIgnoreCase(areaLevel) || "hjss".equalsIgnoreCase(areaLevel) ? areaLevel : "hjs");
	}

	@Override
	public Mono<DataBuffer> queryForExport(LfZdryQO qo) {
		qo.setRylbxList(ListUtils.removeNullElement(qo.getRylbxList()));
		qo.setSfzkList(ListUtils.removeNullElement(qo.getSfzkList()));
		qo.setZrbmList(ListUtils.removeNullElement(qo.getZrbmList()));
		qo.setSsxqList(ListUtils.removeNullElement(qo.getSsxqList()));
		qo.setSsxqIdList(ListUtils.removeNullElement(qo.getSsxqIdList()));
		qo.setGkjbxList(ListUtils.removeNullElement(qo.getGkjbxList()));
		qo.setMjidList(ListUtils.removeNullElement(qo.getMjidList()));
		qo.setSspcsList(ListUtils.removeNullElement(qo.getSspcsList()));
		List<LfZdryEntity> list = mapper.queryExportData(qo);
		// 开始导出
		DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
		OutputStream outputStream = dataBuffer.asOutputStream();
		// 每次写100行数据,就刷新数据出缓存
		SXSSFWorkbook wb = new SXSSFWorkbook(100);
		CellStyle cellStyleLeft = wb.createCellStyle();
		cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
		cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);

		CellStyle cellStyle = wb.createCellStyle();
		cellStyle.setAlignment(HorizontalAlignment.LEFT);
		cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		XSSFFont font = (XSSFFont) wb.createFont();
		font.setFontName("宋体");
		font.setBold(true);// 粗体显示
		font.setFontHeightInPoints((short) 11);

		SXSSFSheet sh = wb.createSheet();
		sh.trackAllColumnsForAutoSizing();
		int totalSize = list == null || list.isEmpty() ? 1 : list.size() + 1;
		for (int i = 0; i < totalSize; i++) {
			Row row = sh.createRow(i);
			for (int j = 0; j < 15; j++) {
				Cell cell = row.createCell(j);
				String title = "";
				if (i == 0) {
					switch (j) {
					case 0: {
						title = "序号";
					}
						break;
					case 1: {
						title = "姓名";
					}
						break;
					case 2: {
						title = "性别";
					}
						break;
					case 3: {
						title = "年龄";
					}
						break;
					case 4: {
						title = "身份证号";
					}
						break;
					case 5: {
						title = "手机号";
					}
						break;
					case 6: {
						title = "户籍地";
					}
						break;
					case 7: {
						title = "现住地";
					}
						break;
					case 8: {
						title = "人员类别";
					}
						break;
					case 9: {
						title = "人员细类";
					}
						break;
					case 10: {
						title = "责任警种";
					}
						break;
					case 11: {
						title = "所属派出所";
					}
						break;
					case 12: {
						title = "管控民警";
					}
						break;
					case 13: {
						title = "管控民警手机号";
					}
						break;
					case 14: {
						title = "备注";
					}
						break;
					}
					cell.setCellValue(title);
					cell.setCellStyle(cellStyle);
				} else {
					LfZdryEntity entity = list.get(i - 1);
					switch (j) {
					case 0: {
						cell.setCellValue(entity.getXh());
					}
						break;
					case 1: {
						cell.setCellValue(entity.getXm());
					}
						break;
					case 2: {
						cell.setCellValue(entity.getXb());
					}
						break;
					case 3: {
						cell.setCellValue(StrUtils.getAgeBySfzh(entity.getSfzh()));
					}
						break;
					case 4: {
						cell.setCellValue(entity.getSfzh());
					}
						break;
					case 5: {
						cell.setCellValue(entity.getSjh());
					}
						break;
					case 6: {
						cell.setCellValue(entity.getHjd());
					}
						break;
					case 7: {
						cell.setCellValue(entity.getXzz());
					}
						break;
					case 8: {
						cell.setCellValue(entity.getRylbx());
					}
						break;
					case 9: {
						cell.setCellValue(entity.getXl());
					}
						break;
					case 10: {
						cell.setCellValue(entity.getZrbm());
					}
						break;
					case 11: {
						cell.setCellValue(entity.getSspcs());
					}
						break;
					case 12: {
						cell.setCellValue(entity.getGkmj());
					}
						break;
					case 13: {
						cell.setCellValue(entity.getMjlxdh());
					}
						break;
					case 14: {
						cell.setCellValue("");
					}
						break;
					}
					cell.setCellStyle(cellStyleLeft);
				}
			}
		}
		try {
			wb.write(outputStream);
		} catch (IOException e) {
			log.error("error == >{}", e.getMessage());
		} finally {
			try {
				wb.close();
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
				log.error("error == >{}", e.getMessage());
			}
		}
		return Mono.just(dataBuffer);
	}

	@Override
	public int getTx(String id) {
		GetImage getImage = new GetImage();
		if (id.equals("all")) {
			List<LfZdryEntity> entitys = this.list();
			entitys.forEach(item -> {
				String fileName = item.getSfzh() + ".jpg";
				String url = this.zdryTxUrl + fileName;
				byte[] btImg = getImage.getImageFromNetByUrl(url);
				if (null != btImg && btImg.length > 0) {
					String fileName1 = this.zdryTxFileAddr + fileName;
					getImage.writeImageToDisk(btImg, fileName1);
				} else {
				}
			});
		} else {
			String fileName = id + ".jpg";
			String url = this.zdryTxUrl + fileName;
			byte[] btImg = getImage.getImageFromNetByUrl(url);
			if (null != btImg && btImg.length > 0) {
				String fileName1 = this.zdryTxFileAddr + fileName;
				getImage.writeImageToDisk(btImg, fileName1);
			} else {
			}

		}
		return 0;
	}

	/**
	 * 获取布控接收对象
	 *
	 * @return
	 */
	@Override
	public Map<Object, Object> queryReceivingInfo() {
		Map<Object, Object> result = new HashMap<>();
		// 卡点警力分布信息列表查询
		List<ContactCardPoliceForceEntity> contactCardPoliceForceEntities = contactCardPoliceForceService
				.list(new QueryWrapper<>());
		result.put("contactCardPoliceForceEntities", contactCardPoliceForceEntities);
		// 警务室巡区信息列表查询
		List<ContactPoliceRoomEntity> contactPoliceRoomEntities = contactPoliceRoomService.list(new QueryWrapper<>());
		result.put("contactPoliceRoomEntities", contactPoliceRoomEntities);

		return result;
	}

	/**
	 * 保存重点人员布控信息
	 *
	 * @param lfZdryControlPcEntity 重点人员布控pc信息
	 * @return
	 */
	@Override
	public boolean saveZdryControlPc(LfZdryControlPcEntity lfZdryControlPcEntity) {
		Boolean result = false;

		if (null == lfZdryControlPcEntity) {
			throw new BusinessException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "lfZdryControlPc对象不能为空");
		}
		Boolean isSuccess = false;

		Date nowDate = new Date();
		if (StringUtils.isBlank(lfZdryControlPcEntity.getId())) {
			lfZdryControlPcEntity.setStatus(1);
			lfZdryControlPcEntity.setCreateTime(nowDate);
			isSuccess = lfZdryControlPcService.save(lfZdryControlPcEntity);
		} else {
			lfZdryControlPcEntity.setUpdateTime(nowDate);
			isSuccess = lfZdryControlPcService.updateById(lfZdryControlPcEntity);
		}

		List<LfZdryControlPcReceiveEntity> lfZdryControlPcReceiveEntities = lfZdryControlPcEntity
				.getZdryControlPcReceiveEntities();
		lfZdryControlPcReceiveEntities.forEach(entity -> {
			entity.setControlId(lfZdryControlPcEntity.getId());
			entity.setCreateTime(nowDate);
		});
		if (isSuccess) {
			result = lfZdryControlPcReceiveService.saveBatch(lfZdryControlPcReceiveEntities);
		}
		return result;
	}

	@Override
	public IPage<LfZdryEntity> pageData(Integer page, Integer size, String date, String rangeVal, String rangeType) {
		QueryWrapper<LfZdryEntity> queryWrapper = new QueryWrapper<>();
		List<String> vs = StringUtils.isEmpty(rangeVal) ? null : Arrays.asList(rangeVal.split(","));
		queryWrapper.lambda().ge(LfZdryEntity::getCreate_timex, DateUtils.strToDateOrTime(date + " 00:00:00", null))
				.lt(LfZdryEntity::getCreate_timex, DateUtils.strToDateOrTime(date + " 23:59:59", null));
		if (!StringUtils.isEmpty(rangeVal)) {// 范围值不为空
			switch (rangeType) {
			case "1": {
				queryWrapper.lambda().in(LfZdryEntity::getSsxqId, rangeVal);
			}
				break;
			case "2": {
				if (vs != null && !vs.isEmpty())
					queryWrapper.lambda().in(LfZdryEntity::getOid, vs);
			}
				break;
			}
		}
		IPage<LfZdryEntity> iPage = new Page<>();
		iPage.setTotal(this.count(queryWrapper));
		iPage.setRecords(mapper.listZdryByCreateTime(page <= 1 ? 0 : page - 1, size, date, rangeType, vs, null, "1",
				null, null));
		return iPage;
	}

	@Override
	public IPage<LfZdryEntity> listStatisticsPage(Integer page, Integer size, String rangeVal, String rangeType,
			String zrbm, String isApproveFilter, String start, String end) {
		QueryWrapper<LfZdryEntity> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isEmpty(isApproveFilter) && isApproveFilter.equalsIgnoreCase("1"))
			// queryWrapper.lambda().eq(LfZdryEntity::getZdApproveStatus,"4");
			queryWrapper.lambda().eq(LfZdryEntity::getApproveStatus, "4");
		List<String> zrbms = null;
		if (!StringUtils.isEmpty(zrbm)) {
			zrbms = Arrays.asList(zrbm.split(","));
			queryWrapper.lambda().in(LfZdryEntity::getZrbm, zrbms);
		}
		List<String> vs = StringUtils.isEmpty(rangeVal) ? null : Arrays.asList(rangeVal.split(","));
		if (!StringUtils.isEmpty(rangeVal)) {// 范围值不为空
			switch (rangeType) {
			case "1": {
				queryWrapper.lambda().in(LfZdryEntity::getSsxqId, rangeVal);
			}
				break;
			case "2": {
				if (vs != null && !vs.isEmpty())
					queryWrapper.lambda().in(LfZdryEntity::getOid, vs);
			}
				break;
			}
		}
		IPage<LfZdryEntity> iPage = new Page<>();
		iPage.setTotal(this.count(queryWrapper));
		iPage.setRecords(mapper.listZdryByCreateTime(page <= 1 ? 0 : page - 1, size, null, rangeType, vs, zrbms,
				isApproveFilter, start, end));
		return iPage;
	}

	@Override
	public List<LfZdryEntity> listData(String date, String rangeVal, String rangeType) {
		List<String> vs = StringUtils.isEmpty(rangeVal) ? null : Arrays.asList(rangeVal.split(","));
		return mapper.listZdryByCreateTime(null, null, date, rangeType, vs, null, "1", null, null);
	}

	public List<ZdryVo> getSimpleAll() {
		return mapper.getSimpleAll();
	}

	private Workbook getWorkBook(File file) throws IOException {
		FileInputStream fileInputStream = new FileInputStream(file);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		IOUtils.copy(fileInputStream, byteArrayOutputStream);
		Workbook workbook;
		try {
			POIFSFileSystem fs = new POIFSFileSystem(file);
			workbook = new HSSFWorkbook(fs);
		} catch (Exception e) {
			workbook = new HSSFWorkbook(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
		}
		return workbook;
	}

	/*@Override
	public List<SpecialPersonStatisticsDataVO> getSpecialPersonStatistics(String rangeType, String rangeVal,
			String zrdws) {
		List<String> list = new ArrayList<>();
		if (!StringUtils.isEmpty(rangeType) && !StringUtils.isEmpty(rangeVal)) {
			list.addAll(Arrays.asList(rangeVal.split(",")));
		}
		List<String> zrdwList = new ArrayList<>();
		if (!StringUtils.isEmpty(zrdws) && !StringUtils.isEmpty(zrdws)) {
			zrdwList.addAll(Arrays.asList(zrdws.split(",")));
		}
		return mapper.getSpecialPersonStatistics(rangeType, list, zrdwList);
	}*/

	@Override
	public List<PredictStatisticsDataItem> getPredictSpecialPersonStatistics(String rangeType, String rangeVal,
			String start, String end) {
		List<String> list = new ArrayList<>();
		if (!StringUtils.isEmpty(rangeType) && !StringUtils.isEmpty(rangeVal)) {
			list.addAll(Arrays.asList(rangeVal.split(",")));
		}
		return mapper.getPredictSpecialPersonStatistics(rangeType, list, start, end);
	}

	@Override
	public List<PredictStatisticsDataItem> getPredictEventSpecialPersonStatistics(String rangeType, String rangeVal,
			String start, String end) {
		List<String> list = new ArrayList<>();
		if (!StringUtils.isEmpty(rangeType) && !StringUtils.isEmpty(rangeVal)) {
			list.addAll(Arrays.asList(rangeVal.split(",")));
		}
		return mapper.getDropSpecialPersonStatistics(rangeType, list, start, end);
	}

	@Override
	public String getCiperBySfzh(String sfzh) {
		return mapper.getCiperBySfzh(sfzh);
	}

	@Override
	public void fullLocationInfo(String sfzh) {
		if (!StringUtils.isEmpty(systemConfig.getLocationEnable())
				&& "true".equalsIgnoreCase(systemConfig.getLocationEnable())) {
			List<String> sfzhs = new ArrayList<>(Arrays.asList(sfzh.split(",")));
			if (!sfzhs.isEmpty()) {
				List<LfZdryEntity> zdryEntityList = this
						.list(new LambdaQueryWrapper<LfZdryEntity>().in(LfZdryEntity::getSfzh, sfzhs));
				if (!zdryEntityList.isEmpty()) {
					log.info("开始请求位置服务===>");
					zdryEntityList.forEach(zd -> {
						try {
							ResponseEntity<JSONObject> rJobj = restTemplate.getForEntity(
									systemConfig.getLocationServer() + "?address=" + zd.getXzz(), JSONObject.class);
							Optional.ofNullable(rJobj.getBody())
									.flatMap(item -> Optional.ofNullable(item.getJSONObject("data")))
									.flatMap(
											data -> Optional.ofNullable(data.getJSONArray("poiList")))
									.ifPresent(
											list -> this
													.update(new LambdaUpdateWrapper<LfZdryEntity>()
															.set(LfZdryEntity::getX,
																	list.getJSONObject(0).getDouble("gcjlon")
																			.toString())
															.set(LfZdryEntity::getY,
																	list.getJSONObject(0).getDouble("gcjlat")
																			.toString())
															.eq(LfZdryEntity::getSfzh, zd.getSfzh())));
						} catch (RestClientException e) {
//                            e.printStackTrace();
							log.error("error==>{}", e.getMessage());
						}
					});
				}
			}
		}
	}

	public String getOrgName(String orgId) {

		ResponseEntity result = restTemplate.getForEntity(
				systemConfig.getSystemServer() + "/api/system/organization/getOrgById?id=" + orgId, JSONObject.class);
		if (null != result) {
			if (null != result.getBody()) {
				JSONObject jsonObject = JSONObject.parseObject(result.getBody().toString());
				if (jsonObject.containsKey("data")) {
					JSONObject orgJson = jsonObject.getJSONObject("data");
					String shortName = orgJson.getString("shortName");
					return shortName;
				}
			}
		}
		return null;
	}

	@Override
	public Map<String, String> getAllRegionInfo() {
		Map<String, String> returnMap = null;
		try {
			ResponseEntity result = restTemplate.getForEntity(
					systemConfig.getSystemServer() + "api/system/region/getAllRegionInfo", JSONObject.class);
			returnMap = new HashMap<>();
			if (null != result) {
				if (null != result.getBody()) {
					JSONObject jsonObject = JSONObject.parseObject(result.getBody().toString());
					if (jsonObject.containsKey("data")) {
						List<Map> regiones = JSONArray.parseArray(jsonObject.get("data").toString(), Map.class);
						for (Map map : regiones) {
							returnMap.put((String) map.get("id"), (String) map.get("regionName"));
						}
					}
				}
			}
		} catch (RestClientException e) {
			e.getMessage();
		}
		return returnMap;
	}

	public Map<String, String> getZrpcs(String orgType) {
		ResponseEntity result = restTemplate.getForEntity(
				systemConfig.getSystemServer() + "/api/system/organization/getOrgByOrgtype?orgType=" + orgType,
				JSONObject.class);
		Map<String, String> returnMap = new HashMap<>();
		if (null != result) {
			if (null != result.getBody()) {
				JSONObject obj = JSONObject.parseObject(result.getBody().toString());
				List<Map> res = JSONArray.parseArray(obj.get("data").toString(), Map.class);
				for (Map map : res) {
					returnMap.put((String) map.get("id"), (String) map.get("shortName"));
				}
			}
		}
		return returnMap;
	}

	@Override
	public boolean reviewProcess(ServerWebExchange exchange,LfZdryTempEntity entity ) {
		 AccountBo bo = requestUtils.getCurrentUser(exchange);
     	if(bo==null) {
     		throw new BusinessException(10019,"此账号已在别处登录，请查证");
     	}
     	String role = bo.getRoleList().get(0).getRoleType();
     	
     	//审批方法
     	if(role.equals(RoleType.BREACH_REVIEW_DATA.getType())){ // 分局用户
            if("同意".equals(entity.getReviewState())){
            	if(entity.getProcessType()==3) {
            		 entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
            	 }else {
            		 entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
            	 }
                  entity.setLastOperate("同意");
             }else{
                 entity.setApproveStatus(ApproveStatus.REJECT_REVIEWED.getStatus());
                 entity.setLastOperate("驳回");
             }
         }else if(role.equals(RoleType.OWNER_REVIEW_DATA.getType())){ // 警种用户
            if("同意".equals(entity.getReviewState())){
            	entity.setLastOperate("同意");
            	entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
            	/*if(entity.getProcessType()==3 || entity.getProcessType()==2) {
            	}else {
            		entity.setApproveStatus(ApproveStatus.INFO_CENTER_REVIEWED.getStatus());
            	}*/
             }else{
            	 entity.setLastOperate("驳回");
            	 if(RoleType.POLICE_STATION_DATA.getType().equals(entity.getSubmitterRoleId())) {
                     entity.setApproveStatus(ApproveStatus.REJECT_REVIEWED.getStatus());
            	 }else{
            		 //提交人角色为非派出所，则驳回至分局状态
            		 entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
            	 }
             }
         }/*else if(role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())){ // 情报中心 逻辑暂时拿掉
             if("pass".equals(entity.getReviewState())){
                  entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
             }else{
                 entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
             }
         }*/
	     if(!ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus())) {
	    	 if("驳回".equals(entity.getReviewState())) {
	    		 
	    	 }
	     	tempZdryMapper.updateById(entity);
	     }else {
	    	 //完成的逻辑
	    	 LfZdryEntity zdry = new LfZdryEntity();
	    	 BeanUtils.copyProperties(entity,zdry );
	    	 LfZdryTempEntity temp = tempZdryMapper.selectById(entity.getId());
	    	 LfZdryEntity zdry2 = new LfZdryEntity();
	    	 BeanUtils.copyProperties(temp,zdry2 );
	    	 if(mapper.selectById(entity.getId())==null) {
	    		 mapper.insert(zdry2);
	    	 }else {
	    		 mapper.updateById(zdry2);
	    	 }
	    	 mapper.updateById(zdry);
	    	 tempZdryMapper.deleteById(entity.getId());
	     }
	     // 记录审批日志
		 LfZdryApproveLogEntity logEntity = new LfZdryApproveLogEntity();
		 logEntity.setCreator(bo.getPersonBo().getName());
		 logEntity.setSpId(entity.getId());
		 logEntity.setApproveResult(entity.getApproveStatus());
		 logEntity.setApproveStatus(entity.getReviewState());
		 logEntity.setOperation(entity.getReviewState());
		 logEntity.setOperateDept(bo.getOrganizationBo().getShortName());
		 logEntity.setAddition(entity.getApprovalOpinion());
//		 iSpecialPersonService.approveKMSpecialPerson(logEntity);
     	 return true;

	}

	@Override
	public LfZdryTempEntity getDetailById(String id) {
		return Optional.ofNullable(tempZdryMapper.selectById(id))
				.orElseThrow(() -> new BusinessException(500, "人员信息不存在"));
	}

	@Override
	@Transactional
	public boolean transfer(ServerWebExchange exchange, LfZdryEntity entity) {
		AccountBo bo = requestUtils.getCurrentUser(exchange);
		LfZdryTempEntity tempZdry = new LfZdryTempEntity();
		LfZdryEntity oldZdry = mapper.selectById(entity.getId());
		String creator = "";
		int num = 0;
		try {
			if (bo == null) {
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
			// 临时表过度
			//获取分局名称
			String ssfj = oldZdry.getSsxq();
			BeanUtils.copyProperties(entity, tempZdry);
			String role = bo.getRoleList().get(0).getId();
			creator = bo.getPersonBo().getName();
			 //提交人角色ID
	    	entity.setSubmitterRoleId(role);
			if (role.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所用户
				if (entity.getSsxq().equals(ssfj)) {
					entity.setProcessType(3);
					entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
					//num = tempZdryMapper.insert(tempZdry);
				} else  {
					// tempZdry.copy();
					entity.setProcessType(32);
					entity.setApproveStatus(ApproveStatus.BRANCH_REVIEWED.getStatus());
					//num = tempZdryMapper.insert(tempZdry);
				} 
			} else if (role.equals(RoleType.BREACH_REVIEW_DATA.getType())) { // 分局用户
				if (entity.getSsxq().equals(ssfj)) {
					entity.setProcessType(33);
					entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
					//num = mapper.updateById(entity);
				} else{
					// tempZdry.copy();
					entity.setProcessType(34);
					entity.setApproveStatus(ApproveStatus.POLICE_REVIEWED.getStatus());
					//num = tempZdryMapper.insert(tempZdry);
				}
			} else if (role.equals(RoleType.OWNER_REVIEW_DATA.getType())) { // 警种用户
				entity.setProcessType(33);
				entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
				//num = mapper.updateById(entity);
			} else if (role.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 情报中心
				entity.setProcessType(33);
				entity.setApproveStatus(ApproveStatus.COMPLETED.getStatus());
				//num = mapper.updateById(entity);
			}
			
		} catch (Exception e) {
				e.printStackTrace();
		}
		if(ApproveStatus.COMPLETED.getStatus().equals(entity.getApproveStatus())) {
			num = mapper.updateById(entity);
	     }else {
	    	 LfZdryTempEntity zdry = new LfZdryTempEntity();
	    	 LfZdryEntity source = mapper.selectById(entity.getId());
	    	 BeanUtils.copyProperties(source,zdry );
	    	 tempZdryMapper.insert(zdry);
	    	 //分局和派出所字段
	    	 LfZdryTempEntity zdry2 = new LfZdryTempEntity();
	    	 BeanUtils.copyProperties(entity,zdry2 );
	    	 num = tempZdryMapper.updateById(zdry2);
	     }
		
		 // 记录审批日志
 
		 String logRecord =""; //specialPersonComponent.getTransferInfo(entity,oldZdry);
		 LfZdryApproveLogEntity logEntity = new LfZdryApproveLogEntity();
		 logEntity.setCreator(creator);
		 logEntity.setSpId(entity.getId());
		 logEntity.setApproveResult(entity.getApproveStatus());
		 logEntity.setOperation("移交");
		 logEntity.setOperateDept(bo.getOrganizationBo().getShortName());
 
		 logEntity.setAddition(logRecord);
		 //iSpecialPersonService.approveKMSpecialPerson(logEntity);
 
		//历史记录
	   	 LfZdryHistoryLogEntity history = new LfZdryHistoryLogEntity();
         history.setCreator(bo.getPersonBo().getName());
	   	 history.setSpId(entity.getId());
	   	 history.setApproveResult(entity.getApproveStatus());
   		 history.setOperation("提交");
   		 history.setOperateDept(bo.getOrganizationBo().getShortName());
   		 history.setAddition(logRecord);
   		 history.setType(4);
   		lfZdryHistoryLogService.save(history);
		return retBool(num);
	}

	@Override
	public Integer delete(String id) {
		return tempZdryMapper.deleteById(id);
	}
	
	/**
     * 插入或者编辑时设置经纬度
     * @param entity
     */
	@Override
	public FutureTask<Map<String,String>> getLngLat(LfZdryEntity entity){
        Callable<Map<String, String>> callable = new Callable<Map<String, String>>() {
            @Override
            public Map<String, String> call() throws Exception {
                Map<String, String> resultMap = new HashMap<>();
                // 获取现住址地的经纬度
                try {
                   /* Map<String, String> xzzAdress = iSpecialPersonService.searchLngLat(entity.getXzzs(), entity.getXzzsS(), entity.getXzzx(), entity.getXzz());
                    if (null != xzzAdress) {
                        resultMap.put("xzz_x", xzzAdress.get("x"));
                        resultMap.put("xzz_y", xzzAdress.get("y"));
                    }*/

                } catch (Exception e) {
                    log.debug("查询现住址经纬度时发生错误");
                }

                //获取户籍地址的经纬度
                StringBuilder hjSb = new StringBuilder();
                hjSb.append(entity.getHjs()).append(entity.getHjsS()).append(entity.getHjx()).append(entity.getHjd());
                try {
                   /* Map<String, String> hjdAdress = iSpecialPersonService.checkXY(hjSb.toString());
                    if (null != hjdAdress) {
                        resultMap.put("hjd_x", hjdAdress.get("x"));
                        resultMap.put("hjd_y", hjdAdress.get("y"));
                    }*/

                } catch (Exception e) {
                    log.debug("查询户籍地址经纬度时发生时发生错误");
                }
                return resultMap;
            }
        };
        FutureTask<Map<String,String>> futureTask = new FutureTask<>(callable);
        new Thread(futureTask).start();
        return futureTask;
    }
	
	/**
     * 地址转经纬度

     * @param address
     */
	@Override
	public Map<String,String> getCoordinate(AddressQO address){
		long startTime = new Date().getTime();
		Map<String, String> resultMap = new HashMap<>();
		// 获取现住址地的经纬度
		try {
			/*Map<String, String> xzzAdress = specialPersonService.searchLngLat(address.getProvice(), address.getCity(), address.getRegion(), address.getDetailAddress());
			if (null != xzzAdress) {
				resultMap.put("x", xzzAdress.get("x"));
				resultMap.put("y", xzzAdress.get("y"));
			}*/
			
		} catch (Exception e) {
			log.debug("查询现住址经纬度时发生错误");
		}
		long endTime = new Date().getTime();
        log.info("执行查询花费："+(endTime-startTime)/1000);
        return resultMap;
    }



	public List<String> getSfzhsByCondition(ServerWebExchange exchange, LfZdryQO qo){
		 
		setUpAuthority(exchange,qo); //设置权限
		List<String> result = mapper.getSfzhsByCondition(qo);
		return result;
	}

	@Override
	@Transactional
	public void convertAddress(Integer total) {
		QueryWrapper<LfZdryEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().isNull(LfZdryEntity::getHjdX).isNull(LfZdryEntity::getHjdY)
				.isNull(LfZdryEntity::getX).isNull(LfZdryEntity::getY).orderByDesc(LfZdryEntity::getUpdate_timex);
		//CountDownLatch latch = new CountDownLatch(10);
		int startLimit = 0;
		int limitLength = (int)Math.ceil(total/10);
		boolean next = true;
		//ExecutorService es = Executors.newFixedThreadPool(10);
		try {
			log.info("开始执行任务");
			while (next) {
				queryWrapper.last("limit "+limitLength+" offset "+startLimit);
				List<LfZdryEntity> zdryEntities = this.list(queryWrapper);
				executorService.execute(new Runnable() {
					@Override
					public void run() {
						try {
							updateAddress(zdryEntities);
						} catch (Exception e) {
							log.error("转化时发生异常：=====>{}",e.getMessage());
						}finally {
							System.out.println("线程 "+Thread.currentThread().getName()+"执行结束。");
						}
					}
				});
				startLimit += limitLength;
				if ( startLimit> total) {
					next = false;
				}
			}
		} catch (Exception e) {
			log.error("执行更新任务出错");
		}
	}


	private void updateAddress(List<LfZdryEntity> zdryEntities) {
		try {
			for(LfZdryEntity z : zdryEntities){
				List<Map<String,String>> result = AddressResolutionUtil.addressResolution(z.getHjd(), z.getXzz());
				if(null!=result && result.size()>0){
						if(null != result.get(0)){
							z.setHjs(result.get(0).get("province"));
							z.setHjsS(result.get(0).get("city"));
							z.setHjx(result.get(0).get("county"));
							z.setHjd(result.get(0).get("detail"));
						}
						if(null != result.get(1)){
							z.setXzzs(result.get(1).get("province"));
							z.setXzzsS(result.get(1).get("city"));
							z.setXzzx(result.get(1).get("county"));
							z.setXzz(result.get(1).get("detail"));
						}
						/*Map<String,String> hjdMap = iSpecialPersonService.searchLngLat(z.getHjs(),z.getHjsS(),z.getHjdX(),z.getHjd());
						if(null!=hjdMap){
							z.setHjdX(hjdMap.get("x"));
							z.setHjdY(hjdMap.get("y"));
						}*/
					    /*Map<String,String> xzzMap = iSpecialPersonService.searchLngLat(z.getXzzs(),z.getXzzsS(),z.getXzzx(),z.getXzz());
						if(null!=xzzMap){
							z.setX(xzzMap.get("x"));
							z.setY(xzzMap.get("y"));
						}*/
						this.updateById(z);
				}
			}
		} catch (Exception e) {
			log.error("转化时发生异常：=======> {}",e.getMessage());
			//e.printStackTrace();
		}
	}




	/*@Override
	public Object getEveryProvinceZdryNum() {
		return this.getBaseMapper().getEveryProvinceZdryNum();
	}*/

	/*@Override
	public Object getCityZdryNumByProvinceCode(String code) {
		return this.getBaseMapper().getCityZdryNumByProvinceCode(code);
	}*/

	/*@Override
	public Object getCountryZdryNumByCityCode(String code) {
		return this.getBaseMapper().getCountryZdryNumByCityCode(code);
	}*/

	/*@Override
	public Mono<DataBuffer> exportZdryByHjdAndXzz(List<String> sfzhs, String exportName) {
		DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
		OutputStream outputStream = dataBuffer.asOutputStream();
		// 每次写100行数据，就刷新数据出缓存
		SXSSFWorkbook wb = new SXSSFWorkbook(100);

		try {
			CellStyle cellStyleCenter = wb.createCellStyle();
			CellStyle cellStyleLeft = wb.createCellStyle();
			cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
			cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
			cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
			cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
			//加载数据的地方
			List<LfZdryEntity> data = this.list(new QueryWrapper<LfZdryEntity>().lambda().in(LfZdryEntity::getSfzh,sfzhs));
			for(LfZdryEntity zdry : data){
				SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb", zdry.getYjczlb().toString());
				if(null != yjczlbdictEntity)
					zdry.setYjczlbName(yjczlbdictEntity.getValue());
				SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx",zdry.getRysx().toString());
				if(null != rysxdictEntity)
				    zdry.setRysxName(rysxdictEntity.getValue());
			}
			Map<String,String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/zdryInfoHjdAndXzz.json",Map.class);
			ExeclUtil.genExcel(wb,cellStyleCenter,cellStyleLeft,data,LfZdryEntity.class,proTitleMap,"重点人员信息");
			wb.write(outputStream);
		} catch (Exception e) {
			log.info("导出execl时发生异常：======>{}",e.getMessage());
		}finally {
			try {
				wb.close();
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
				log.info("关闭流时发生异常：======> {}",e.getMessage());
			}
		}
		return Mono.just(dataBuffer);
	}*/


	/*@Override
	public List<Map<String,Object>> queryZdryList(ServerWebExchange exchange, LfZdryQO qo) {
		setUpAuthority(exchange,qo); //设置权限
		List<Map<String,Object>> result = mapper.queryZdryList(qo);
		return result;
	}*/

	/*@Override
	public Object queryProvinceTx(ServerWebExchange exchange, LfZdryQO qo) {
		setUpAuthority(exchange,qo); //设置权限
		return mapper.queryProvinceTx(qo);
	}*/

	@Override
	public Object queryCityTx(ServerWebExchange exchange, LfZdryQO qo) {
		setUpAuthority(exchange,qo); //设置权限
		return mapper.queryCityTx(qo);
	}

	/*@Override
	public IPage<LfZdryEntity> queryProvinceAndCityTxList(ServerWebExchange exchange, LfZdryQO qo) {
		Page<LfZdryEntity> page = new Page<>(qo.getStart(),qo.getSize());
		setUpAuthority(exchange,qo); //设置权限
		IPage<LfZdryEntity> result = null;
		if(qo.getQxSign() != null && qo.getQxSign().equals("province")){
			result = this.getBaseMapper().queryProvinceTxList(page,qo);
		}else if(qo.getQxSign() != null && qo.getQxSign().equals("city")){
			result = this.getBaseMapper().queryCityTxList(page,qo);
		}
		if(null !=  result.getRecords() && result.getRecords().size()>0){
				for(LfZdryEntity zdry : result.getRecords()){
					//人员属性
					SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx",String.valueOf(zdry.getRysx()));
					if(null != rysxdictEntity){
						zdry.setRysxName(rysxdictEntity.getValue());
					}
					//预警处置级别
					SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb",String.valueOf(zdry.getYjczlb()));
					if(null!= yjczlbdictEntity){
						zdry.setYjczlbName(yjczlbdictEntity.getValue());
					}
				 }
		} 
		return result;
	}*/

	/*@Override
	public Mono<DataBuffer> exportZdryProvinceAndCityQxData(LfZdryQO qo, String exportName, ServerWebExchange exchange) {
		DefaultDataBuffer dataBuffer = new DefaultDataBufferFactory().allocateBuffer();
		OutputStream outputStream = dataBuffer.asOutputStream();
		// 每次写100行数据，就刷新数据出缓存
		SXSSFWorkbook wb = new SXSSFWorkbook(100);

		try {
			CellStyle cellStyleCenter = wb.createCellStyle();
			CellStyle cellStyleLeft = wb.createCellStyle();
			cellStyleCenter.setAlignment(HorizontalAlignment.CENTER); // 居中
			cellStyleCenter.setVerticalAlignment(VerticalAlignment.CENTER); // 居中
			cellStyleLeft.setAlignment(HorizontalAlignment.LEFT);
			cellStyleLeft.setVerticalAlignment(VerticalAlignment.CENTER);
			//加载数据的地方
			setUpAuthority(exchange,qo); //设置权限
			List<LfZdryEntity> result = null;
			if(qo.getQxSign() != null && qo.getQxSign().equals("province")){
				result = this.getBaseMapper().queryExportProvinceTxList(qo);
			}else if(qo.getQxSign() != null && qo.getQxSign().equals("city")){
				result = this.getBaseMapper().queryExportCityTxList(qo);
			}
			 
			for(LfZdryEntity z : result){
				//人员属性
				SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx",String.valueOf(z.getRysx()));
				if(null != rysxdictEntity){
					z.setRysxName(rysxdictEntity.getValue());
				}
 
				//预警处置级别
				SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb",String.valueOf(z.getYjczlb()));
				if(null!= yjczlbdictEntity){
					z.setYjczlbName(yjczlbdictEntity.getValue());
				}
			}
		
			Map<String,String> proTitleMap = JsonFileParseUtil.readJsonFromClassPath("json/zdryInfoHjdAndXzz.json",Map.class);
			ExeclUtil.genExcel(wb,cellStyleCenter,cellStyleLeft,result,LfZdryEntity.class,proTitleMap,"重点人员迁徙信息");
			wb.write(outputStream);
		} catch (Exception e) {
			log.info("导出execl时发生异常：======>{}",e.getMessage());
		}finally {
			try {
				wb.close();
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
				log.info("关闭流时发生异常：======> {}",e.getMessage());
			}
		}
 
		return Mono.just(dataBuffer);
	}*/
	/*@Override
	public IPage<LfZdryEntity> queryZdry(Map<String,Object> paramMap) {
		Page<LfZdryEntity> page = new Page<>((int)paramMap.get("offset"),(int)paramMap.get("pageSize"));
		IPage<LfZdryEntity> result = this.page(page,new QueryWrapper<LfZdryEntity>().lambda().in(LfZdryEntity::getSfzh,(List<String>)paramMap.get("sfzhs")));
		for(LfZdryEntity z : result.getRecords()){
			//人员属性
			SysDictEntity rysxdictEntity = iSysDictService.getEntityByKey("zdry_ryxx",String.valueOf(z.getRysx()));
			if(null != rysxdictEntity){
				z.setRysxName(rysxdictEntity.getValue());
			}
 
			//预警处置级别
			SysDictEntity yjczlbdictEntity = iSysDictService.getEntityByKey("zdry_yjczlb",String.valueOf(z.getYjczlb()));
			if(null!= yjczlbdictEntity){
				z.setYjczlbName(yjczlbdictEntity.getValue());
			}
		}
		return result;
	}*/


	/**
	 * 在查询条件中设置  权限相关的参数
	 * @param exchange
	 * @param qo
	 */
	private void setUpAuthority(ServerWebExchange exchange, LfZdryQO qo) {

		try {
			// 权限相关代码
			AccountBo bo = requestUtils.getCurrentUser(exchange);
			if (bo == null) {
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
			String roleType = bo.getRoleList().get(0).getRoleType();
			String orgName = bo.getOrganizationBo().getShortName();
			// getOrgName(bo.getOrgId());
			// 1、管理员、市局情报中心,不加判断条件
			// 2、市局各警种
			// 角色类型："管理员", "0")"市局情报中心", "1"), "市局警种", "2"),"分局", "3"),"派出所", "4")
			// 审批状态：0：待分局审批,1：待警种审核,2：已驳回,3：已完成, 4：上报
			if (roleType.equals(RoleType.OWNER_ADMIN_ORG_DATA.getType())) { // 1:市局情报中心
				qo.setSsxqList(qo.getQueryList());
			} else if (roleType.equals(RoleType.OWNER_REVIEW_DATA.getType())
					|| roleType.equals(RoleType.OWNER_ORG_DATA.getType())) { // 5:市局警种和2:市局警种审核
				qo.setZrbm(orgName);
				qo.setSsxqList(qo.getQueryList());
			} else if (roleType.equals(RoleType.BREACH_REVIEW_DATA.getType())
					|| roleType.equals(RoleType.BREACH_DATA.getType())) { // 6:分局 和 3:分局审核
				qo.setSsxq(orgName);
				log.info("============qo=========:" + qo);
				/*
				 * if(qo.getQueryList()!=null&&!qo.getQueryList().contains("其他")) { }
				 */
				if(null!=qo.getQueryList()) {
					List<String> list = new ArrayList<String>();
					for (String pcs : qo.getQueryList()) {
						list.add(qo.getSsxq() + pcs);
					}
					qo.setSspcsList(list);
				}
 
			} else if (roleType.equals(RoleType.POLICE_STATION_DATA.getType())) { // 派出所4
				qo.setSspcs(orgName);
				qo.setMjList(qo.getQueryList());
			}
 
		} catch (BusinessException e) {
			log.info("权限参数异常或者筛选参数异常：======>{}",e.getMessage());
			if("此账号已在别处登录，请查证".equals(e.getMessage())){
				throw new BusinessException(10019,"此账号已在别处登录，请查证");
			}
		}
	}

	/**
	 * 根据所属辖区和人员类别统计人数及小类名称
	 * @return
	 */
	public List<Map<String,Object>> getRiskLevelCount(String sspcs,String ssxq,String rylb){
		List<Map<String, Object>> riskLevelCount = mapper.getRiskLevelCount( sspcs, ssxq, rylb);
		return riskLevelCount;
	}
}